//RandomAcessFile的用法，给出案例
import java.io.RandomAccessFile;
import java.io.IOException;

public class RandomAccessFileExample {
    public static void main(String[] args) {
        String fileName = "example.dat";

        // 写入数据到文件
        try (RandomAccessFile raf = new RandomAccessFile(fileName, "rw")) {
            // 写入一些整数
            for (int i = 1; i <= 5; i++) {
                raf.writeInt(i);
            }
            System.out.println("Data written to file.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取数据从文件
        try (RandomAccessFile raf = new RandomAccessFile(fileName, "r")) {
            // 读取文件中的整数
            System.out.println("Reading data from file:");
            for (int i = 0; i < 5; i++) {
                int value = raf.readInt();
                System.out.println("Value " + (i + 1) + ": " + value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 更新数据在文件
        try (RandomAccessFile raf = new RandomAccessFile(fileName, "rw")) {
            // 移动到第一个整数的位置并更新它
            raf.seek(0); // 第一个整数的位置是 0
            raf.writeInt(10); // 更新第一个整数为 10
            System.out.println("Updated first value to 10.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 再次读取数据
        try (RandomAccessFile raf = new RandomAccessFile(fileName, "r")) {
            System.out.println("Reading data after update:");
            for (int i = 0; i < 5; i++) {
                int value = raf.readInt();
                System.out.println("Value " + (i + 1) + ": " + value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
